﻿@page "/pages/contacts"

@using CleanArchitecture.Blazor.Application.Features.Contacts.Caching
@using CleanArchitecture.Blazor.Application.Features.Contacts.DTOs
@using CleanArchitecture.Blazor.Application.Features.Contacts.Specifications
@using CleanArchitecture.Blazor.Application.Features.Contacts.Commands.Delete
@using CleanArchitecture.Blazor.Application.Features.Contacts.Commands.Import
@using CleanArchitecture.Blazor.Application.Features.Contacts.Queries.Export
@using CleanArchitecture.Blazor.Application.Features.Contacts.Queries.Pagination
@using CleanArchitecture.Blazor.Application.Features.Contacts.Commands.AddEdit
@using CleanArchitecture.Blazor.Server.UI.Pages.Contacts.Components

@inject IStringLocalizer<Contacts> L
@inject BlazorDownloadFileService BlazorDownloadFileService

@attribute [Authorize(Policy = Permissions.Contacts.View)]
<PageTitle>@Title</PageTitle>

<MudDataGrid ServerData="@(ServerReload)"
             FixedHeader="true"
             FixedFooter="false"
             Virtualize="false"
             @bind-RowsPerPage="_defaultPageSize"
             Loading="@_loading"
             MultiSelection="true"
             T="ContactDto"
             SelectOnRowClick="false"
             RowClick="@(s => OnDataGridRowClick(s.Item))"
             @bind-SelectedItems="_selectedContacts"
             Hover="true" @ref="_contactsGrid">
    <ToolBarContent>
        <MudStack Row Spacing="0" Class="flex-grow-1" Justify="Justify.SpaceBetween">
            <MudStack Row AlignItems="AlignItems.Start">
                <MudIcon Icon="@Icons.Material.Filled.Window" Size="Size.Large" />
                <MudStack Spacing="0">
                    <MudText Typo="Typo.subtitle2" Class="mb-2">@Title</MudText>
                    <MudEnumSelect Style="min-width:120px" TEnum="ContactListView" ValueChanged="OnListViewChanged" Value="_contactsQuery.ListView" Dense="true" Label="@L["List View"]">
                    </MudEnumSelect>
                </MudStack>
            </MudStack>
            <MudStack Spacing="0" AlignItems="AlignItems.End">
                <MudToolBar Dense WrapContent="true" Class="py-1 px-0">
                    <MudButton Disabled="@_loading"
                               OnClick="@(() => OnRefresh())"
                               StartIcon="@Icons.Material.Outlined.Refresh">
                        @ConstantString.Refresh
                    </MudButton>
                    @if (_accessRights.Create)
                    {
                        <MudButton StartIcon="@Icons.Material.Outlined.Add"
                                   OnClick="OnCreate">
                            @ConstantString.New
                        </MudButton>
                    }
                    <MudMenu TransformOrigin="Origin.BottomRight" AnchorOrigin="Origin.BottomRight" EndIcon="@Icons.Material.Filled.MoreVert" Label="@ConstantString.More">
                        @if (_accessRights.Create)
                        {
                            <MudMenuItem Disabled="@(_selectedContacts.Count != 1)" OnClick="OnCloneContact">@ConstantString.Clone</MudMenuItem>
                        }
                        @if (_accessRights.Delete)
                        {
                            <MudMenuItem Disabled="@(!(_selectedContacts.Count > 0))"
                                         OnClick="OnDeleteSelectedContacts">
                                @ConstantString.Delete
                            </MudMenuItem>
                        }
                        @if (_accessRights.Export)
                        {
                            <MudMenuItem Disabled="@_exporting"
                                         OnClick="OnExport">
                                @ConstantString.Export
                            </MudMenuItem>
                        }
                        @if (_accessRights.Import)
                        {
                            <MudMenuItem>
                                <MudFileUpload T="IBrowserFile" FilesChanged="OnImportData" Accept=".xlsx">
                                    <ActivatorContent>
                                        <MudButton Class="pa-0 ma-0" Style="font-weight:400;text-transform:none;"
                                                   Variant="Variant.Text"
                                                   Disabled="@_uploading">
                                            @ConstantString.Import
                                        </MudButton>
                                    </ActivatorContent>
                                </MudFileUpload>
                            </MudMenuItem>
                        }
                    </MudMenu>
                </MudToolBar>
                <MudStack Row Spacing="1">
                    @if (_accessRights.Search)
                    {
                        <MudTextField T="string" ValueChanged="@(s => OnSearch(s))" Value="@_contactsQuery.Keyword" Placeholder="@ConstantString.Search" Adornment="Adornment.End"
                                      AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Small">
                        </MudTextField>
                    }
                </MudStack>
            </MudStack>
        </MudStack>
    </ToolBarContent>
    <Columns>
        <SelectColumn ShowInFooter="false"></SelectColumn>
        <TemplateColumn HeaderStyle="width:60px" Title="@ConstantString.Actions" Sortable="false">
            <CellTemplate>
                @if (_accessRights.Edit || _accessRights.Delete)
                {
                    <MudMenu Icon="@Icons.Material.Filled.Edit" Variant="Variant.Filled" Size="Size.Small"
                             Dense="true"
                             EndIcon="@Icons.Material.Filled.KeyboardArrowDown" IconColor="Color.Info" AnchorOrigin="Origin.CenterLeft">
                        @if (_accessRights.Edit)
                        {
                            <MudMenuItem OnClick="@(() => OnEditContact(context.Item))">@ConstantString.Edit</MudMenuItem>
                        }
                        @if (_accessRights.Delete)
                        {
                            <MudMenuItem OnClick="@(() => OnDeleteContact(context.Item))">@ConstantString.Delete</MudMenuItem>
                        }
                    </MudMenu>
                }
                else
                {
                    <MudIconButton Variant="Variant.Filled"
                                   Disabled="true"
                                   Icon="@Icons.Material.Filled.DoNotTouch"
                                   Size="Size.Small"
                                   Color="Color.Surface">
                        @ConstantString.NoAllowed
                    </MudIconButton>
                }
            </CellTemplate>
        </TemplateColumn>
        @*TODO: Define the fields that should be displayed in data table*@
        <PropertyColumn Property="x => x.Name" Title="@L[_contactDto.GetMemberDescription(x => x.Name)]">
            <CellTemplate>
                <div class="d-flex flex-column">
                    <MudText Typo="Typo.body1">@context.Item.Name</MudText>
                    <MudText Typo="Typo.body2" Class="mud-text-secondary">@context.Item.Description</MudText>
                </div>
            </CellTemplate>
        </PropertyColumn>
        <PropertyColumn Property="x => x.Email" Title="@L[_contactDto.GetMemberDescription(x => x.Email)]" />
        <PropertyColumn Property="x => x.PhoneNumber" Title="@L[_contactDto.GetMemberDescription(x => x.PhoneNumber)]" />
        <PropertyColumn Property="x => x.Country" Title="@L[_contactDto.GetMemberDescription(x => x.Country)]" />

    </Columns>
    <NoRecordsContent>
        <MudText>@ConstantString.NoRecords</MudText>
    </NoRecordsContent>
    <LoadingContent>
        <MudText>@ConstantString.Loading</MudText>
    </LoadingContent>
    <PagerContent>
        <MudDataGridPager PageSizeOptions="@(new int[] { 10, 15, 30, 50, 100, 500, 1000 })" />
    </PagerContent>
</MudDataGrid>



@code {
    public string? Title { get; private set; }
    private int _defaultPageSize = 15;
    private HashSet<ContactDto> _selectedContacts = new HashSet<ContactDto>();
    private MudDataGrid<ContactDto> _contactsGrid = default!;
    private ContactDto _contactDto = new();
    private bool _loading;
    private bool _uploading;
    private bool _exporting;
    [CascadingParameter]
    private Task<AuthenticationState> AuthState { get; set; } = default!;
    [CascadingParameter]
    private UserProfile? UserProfile { get; set; }


    private ContactsWithPaginationQuery _contactsQuery { get; set; } = new();
    private ContactsAccessRights _accessRights = new();

    protected override async Task OnInitializedAsync()
    {
        Title = L[_contactDto.GetClassDescription()];
        _accessRights = await PermissionService.GetAccessRightsAsync<ContactsAccessRights>();
    }

    private async Task<GridData<ContactDto>> ServerReload(GridState<ContactDto> state)
    {
        try
        {
            _loading = true;
            _contactsQuery.CurrentUser = UserProfile;
            var sortDefinition = state.SortDefinitions.FirstOrDefault();
            _contactsQuery.OrderBy = sortDefinition?.SortBy ?? "Id";
            _contactsQuery.SortDirection = (sortDefinition != null && sortDefinition.Descending)
                                      ? SortDirection.Descending.ToString()
                                      : SortDirection.Ascending.ToString();
            _contactsQuery.PageNumber = state.Page + 1;
            _contactsQuery.PageSize = state.PageSize;
            var result = await Mediator.Send(_contactsQuery).ConfigureAwait(false);
            return new GridData<ContactDto>() { TotalItems = result.TotalItems, Items = result.Items };
        }
        finally
        {
            _loading = false;
        }

    }
    private async Task OnSearch(string text)
    {
        _selectedContacts.Clear();
        _contactsQuery.Keyword = text;
        await _contactsGrid.ReloadServerData();
    }
    private async Task OnListViewChanged(ContactListView listview)
    {
        _contactsQuery.ListView = listview;
        await _contactsGrid.ReloadServerData();
    }
    private async Task OnRefresh()
    {
        ContactCacheKey.Refresh();
        _selectedContacts.Clear();
        _contactsQuery.Keyword = string.Empty;
        await _contactsGrid.ReloadServerData();
    }
    private Task ShowEditFormDialog(string title, AddEditContactCommand command)
    {
        return DialogServiceHelper.ShowFormDialogAsync<ContactFormDialog, AddEditContactCommand>(
            title,
            command,
            async () =>
            {
                await _contactsGrid.ReloadServerData();
                _selectedContacts.Clear();
            });
    }
    private void OnDataGridRowClick(ContactDto dto)
    {
        Navigation.NavigateTo($"/pages/contacts/view/{dto.Id}");
    }
    private Task OnCreate()
    {
        var command = new AddEditContactCommand();
        return ShowEditFormDialog(L["New Contact"], command);
    }
    private Task OnCloneContact()
    {
        var dto = _selectedContacts.First();
        var command = new AddEditContactCommand()
        {
            Name = dto.Name,
            Description = dto.Description,
            Email = dto.Email,
            PhoneNumber = dto.PhoneNumber,
            Country = dto.Country
        };
        return ShowEditFormDialog(L["Clone Contact"], command);
    }
    private Task OnEditContact(ContactDto dto)
    {
        //var command = Mapper.Map<AddEditContactCommand>(dto);
        //await ShowEditFormDialog(L["Edit Contact"], command);
        Navigation.NavigateTo($"/pages/contacts/edit/{dto.Id}");
        return Task.CompletedTask;
    }
    private Task OnDeleteContact(ContactDto dto)
    {
        var contentText = string.Format(ConstantString.DeleteConfirmation, dto.Name);
        var command = new DeleteContactCommand(new int[] { dto.Id });
        return DeleteContactsInternal(command, contentText);
    }

    private Task OnDeleteSelectedContacts()
    {
        var contentText = string.Format(ConstantString.DeleteConfirmWithSelected, _selectedContacts.Count);
        var command = new DeleteContactCommand(_selectedContacts.Select(x => x.Id).ToArray());
        return DeleteContactsInternal(command, contentText);
    }

    private Task DeleteContactsInternal(DeleteContactCommand command, string contentText)
    {
        return DialogServiceHelper.ShowDeleteConfirmationDialogAsync(
            command,
            ConstantString.DeleteConfirmationTitle,
            contentText,
            async () =>
            {
                await _contactsGrid.ReloadServerData();
                _selectedContacts.Clear();
            });
    }

    private async Task OnExport()
    {
        _exporting = true;
        var request = new ExportContactsQuery()
        {
            Keyword = _contactsQuery.Keyword,
            CurrentUser = UserProfile,
            ListView = _contactsQuery.ListView,
            OrderBy = _contactsGrid.SortDefinitions.Values.FirstOrDefault()?.SortBy ?? "Id",
            SortDirection = (_contactsGrid.SortDefinitions.Values.FirstOrDefault()?.Descending ?? true) ? SortDirection.Descending.ToString() : SortDirection.Ascending.ToString()
        };
        var result = await Mediator.Send(request);
        await result.MatchAsync(
            async data =>
            {
                await BlazorDownloadFileService.DownloadFileAsync($"{L["Contacts"]}.xlsx", result.Data!, contentType: "application/octet-stream");
                Snackbar.Add($"{ConstantString.ExportSuccess}", MudBlazor.Severity.Info);
            },
            errors =>
            {
                Snackbar.Add($"{errors}", MudBlazor.Severity.Error);
                return Task.CompletedTask;
            });
        _exporting = false;
    }
    private async Task OnImportData(IBrowserFile file)
    {
        _uploading = true;
        var stream = new MemoryStream();
        await file.OpenReadStream().CopyToAsync(stream);
        var command = new ImportContactsCommand(file.Name, stream.ToArray());
        var result = await Mediator.Send(command);
        await result.MatchAsync(
            async data =>
            {
                await _contactsGrid.ReloadServerData();
                Snackbar.Add($"{ConstantString.ImportSuccess}", MudBlazor.Severity.Info);
            }, errors =>
            {
                Snackbar.Add($"{errors}", MudBlazor.Severity.Error);
                return Task.CompletedTask;
            });
        _uploading = false;
    }

}
